<template>
  <Form class="xtx-form" :validation-schema='veeValidateSchema' v-slot='{errors}' ref="formCom">
    <div class="user-info" v-if="qqUserInfo.data">
      <img :src="qqUserInfo.data.figureurl_1" alt="" />
      <p>Hi，{{qqUserInfo.nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field" style="color:red">
        <i class="icon iconfont icon-phone"></i>
        <Field name='mobile' class="input" type="text" placeholder="绑定的手机号" v-model="from.mobile" :class="{err:errors.mobile}" />{{errors.mobile}}
      </div>
      <div class="error"></div>
    </div>
    <div class="xtx-form-item">
      <div class="field" style="color:red">
        <i class="icon iconfont icon-code"></i>
        <Field name='code' class="input" type="text" placeholder="短信验证码" v-model="from.code"  :class="{err:errors.code}" />{{errors.code}}
        <span class="code" @click="sendcode" v-text="time!=60?time:'发送验证码'"></span>
      </div>
      <div class="error"></div>
    </div>
    <a href="javascript:;" class="submit" @click="bindbtn">立即绑定</a>
  </Form>
</template>

<script>
import { qqcode, bindqq } from '@/api/login'
import Message from '@/components/library/Message'
import veeValidateSchema from '@/utils/vee-validate-schema'
import { useIntervalFn } from '@vueuse/core'
// 引入验证组件，field是给要验证每一项使用的，form是给包裹要验证的标签使用的
import { Field, Form } from 'vee-validate'
import { inject, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  // 注册组件
  components: {
    Field,
    Form
  },
  setup () {
    //   from储存数据
    const from = ref({
      mobile: '',
      code: ''
    })
    // 定时器默认60秒
    const time = ref(60)

    // 从useIntervalFn里解构出resume和pause,resume是开始计时函数，pause停止函数
    const { resume, pause } = useIntervalFn(() => {
      time.value--
      //   // 停止
      if (time.value === 0) {
        pause()
        time.value = 60
      }
    //   immediate是默认是否执行
    }, 100, { immediate: false })
    // 发送验证码函数
    const sendcode = async () => {
      const a = veeValidateSchema.mobile(from.value.mobile)
      if (a === true) {
        //   try尝试{这里边写逻辑}catch是如果尝试做的逻辑有错误则在这里执行可以接收一个错误对象（error）
        try {
          const qq = await qqcode(from.value.mobile)
          console.log(qq)
          resume()
          Message('success', '发送成功')
        } catch (error) {
          Message('warn', error.response.data.message)
        }
      }
    }
    const store = useStore()
    const router = useRouter()
    const formCom = ref(null)
    // 获取父组件用provide传过来的qqUserInfo数据，用inject获取
    const qqUserInfo = inject('qqUserInfo')
    console.log(qqUserInfo)
    // 点击绑定按钮执行的函数
    const bindbtn = async () => {
      // 调用validate函数接收校验表单（formCom）的结果
      const validateForm = await formCom.value.validate()
      if (qqUserInfo && validateForm) {
        try {
          const { result } = await bindqq({ unionld: inject.openId, mobile: from.value.mobile, code: from.value.code })
          store.commit('user/setUser', result)
          router.push(store.state.user.url)
          Message('success', '绑定成功')
        } catch (error) {
          Message('error', error.response.data.message)
          // console.log(error)
        }
      }
    }
    return { qqUserInfo, veeValidateSchema, from, sendcode, time, bindbtn, formCom }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
